/*=+--+=#=+--     Unmanned Aerial System Management Software      --+=#=+--+=#*\
|          Copyright (C) 2011 Regents of the University of Colorado.           |
|                             All Rights Reserved.                             |

     This program is free software: you can redistribute it and/or modify
     it under the terms of the GNU General Public License version 2 as
     published by the Free Software Foundation.

     This program is distributed in the hope that it will be useful,
     but WITHOUT ANY WARRANTY; without even the implied warranty of
     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     GNU General Public License for more details.

     You should have received a copy of the GNU General Public License
     along with this program.  If not, see <http://www.gnu.org/licenses/>.

            Jack Elston                       Cory Dixon                        
|           elstonj@colorado.edu              dixonc@colorado.edu              |
|                                                                              |
\*=+--+=#=+--                 --+=#=+--+=#=+--                    --+=#=+--+=#*/

/*!
  \file gpsParser.cxx
  \brief class implemenation for gpsParser

  \author Jack Elston
  $Date: 2005/02/12 00:20:45 $
*/

#include <unistd.h>
#include <signal.h>
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <fcntl.h>

#include "pthParser.h"

/*<-------Defines--------->*/
/*<------End Defines------>*/

/*<---Global Variables---->*/
extern bool verbose;
/*<-End Global Variables-->*/

PTHParser::PTHParser(String name, int a_port) : ThreadedPipe(name)
{
	buf_ptr = 0;
	pth.temp = 0;
	pth.internal_temp = 0;
	pth.rh1 = 0;
	pth.rh2 = 0;

	port = a_port;
}

bool PTHParser::init(ShmStruct * shmStructPtr)
{
	ThreadedPipe::init(shmStructPtr);

	transmit_data = false;
	return true;
}

void PTHParser::update() 
{
	int val, maxFD;
	fd_set readFDs, writeFDs;                   // fd sets
	struct timeval timeout;

	FD_ZERO(&readFDs);	                    		// zero read fd set
	FD_ZERO(&writeFDs);	                    		// zero write fd set
	FD_SET(fifo_FDs[OUTBOARD_RX],&readFDs);			// add fifo
	FD_SET(fifo_FDs[INBOARD_TX],&writeFDs);			// add fifo
	FD_SET(fifo_FDs[OUTBOARD_TX],&writeFDs);		// add fifo

	maxFD = fifo_FDs[OUTBOARD_RX];
	if(fifo_FDs[INBOARD_TX] > maxFD) maxFD = fifo_FDs[INBOARD_TX];
	if(fifo_FDs[OUTBOARD_TX] > maxFD) maxFD = fifo_FDs[OUTBOARD_TX];

	timeout.tv_sec = TIME_OUT_SEC; timeout.tv_usec = TIME_OUT_USEC;

	if( (val = select(maxFD + 1, &readFDs, &writeFDs,NULL,&timeout)) <= 0) {
		if( val != 0 ) {
			if (errno != EINTR) {
				perror("PTHParser::update() select");
				execRate = -1;
			} else
				cout << getName() << "::update() - select interrupted" << endl;
		}
	}
	else {
		if(FD_ISSET(fifo_FDs[OUTBOARD_RX], &readFDs))
		{
			int n = 0;
			n=readFifo(OUTBOARD_RX);
			if(n>0) {
				// process read commands

				if(buf_ptr+n > 255) buf_ptr = 0;

				memcpy(&(buf[buf_ptr]),fifo_msg.data,n);
				buf_ptr += n;

				while (buf_ptr != 0) {

					int size = 0;
					bool full_packet = false; 
					for(; size < buf_ptr; size++) {
						if(buf[size] == 0) {
							//buf[size] = 0;
							full_packet = true;
							break;
						}
					}

					if(full_packet) {
						int frame;
						float pressure, temp, rh1, rh2, internal_temp;
						int retval = sscanf((char *)buf,"%i %f %f %f %f %f", &frame, &pressure, &temp, &rh1, &rh2, &internal_temp);
						if(retval == 6) {
							//printf("%i %f %f %f %f %f\n",frame, pressure, temp, rh1, rh2, internal_temp);
							pth.pressure = pressure;
							pth.temp = temp;
							pth.internal_temp = internal_temp;
							pth.rh1 = rh1;
							pth.rh2 = rh2;
							transmit_data = true;
						}
						if(buf_ptr-(size+1) > 0) { 
							memcpy(buf,&(buf[size+1]),buf_ptr-(size+1));
							buf_ptr = buf_ptr-(size+1);
						}
						else {
							buf_ptr = 0;
						}
					}
					else
						break;
				}
			}
		}
		if(FD_ISSET(fifo_FDs[INBOARD_TX], &writeFDs)) {
			currentStamp.stamp();
			if(transmit_data) {

				CMD_CMD((fifo_msg.data)) = CMD_PTH;
				CMD_NUM((fifo_msg.data)) = sizeof(PTH_t);
				CopyStructToBuf(pth, CMD_DATAPTR(fifo_msg.data));
				CMD_CSUM(fifo_msg.data) = 0;
				CMD_CSUM(fifo_msg.data) = C_calcCheckSum((uint8_t*)fifo_msg.data);

				fifo_msg.size = CMD_SIZE(fifo_msg.data);
				fifo_msg.port = port;

				Client * a_client;
				int i=0;

				while((a_client = shmPtr->clients.getSubscriptionsTo(CMD_PTH,i)) != NULL)
				{
					Client * me = shmPtr->clients.getClient(0);
					fifo_msg.src.s_addr  = shmPtr->clients.getAddr(me, a_client).s_addr;
					fifo_msg.dest.s_addr = shmPtr->clients.getAddr(a_client).s_addr;
					writeFifo(INBOARD_TX);
					i++;
				}
				transmit_data = false;
			}
		}
	}
}
